package com.heba.adapter;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.heba.bean.article.ItemArticleObject;
import com.heba.config.CommonConfig;
import com.heba.greenmulu.ItemArticleDetailActivity;
import com.heba.greenmulu.R;
import com.heba.utils.GlideUtil;

import java.util.List;

/**
 * ItemHomeListAdapter
 * <p>
 * Created by jason on 2018/11/15.
 */

public class ItemHomeListAdapter extends BaseAdapter {

    private Context context;
    private LayoutInflater inflater;
    private List<ItemArticleObject> list;
    private String columnName = "";

    public ItemHomeListAdapter(Context context, List<ItemArticleObject> list, String columnName) {
        this.context = context;
        this.list = list;
        this.inflater = LayoutInflater.from(context);
        this.columnName = columnName;
    }

    @Override
    public int getCount() {
        return list.size();
    }

    @Override
    public Object getItem(int position) {
        return list.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder = null;
        if (convertView == null) {
            holder = new ViewHolder();
            convertView = inflater.inflate(R.layout.item_user_article, parent, false);
            holder.img_photo = convertView.findViewById(R.id.img_photo);
            holder.txt_article = convertView.findViewById(R.id.txt_article);
            holder.txt_name = convertView.findViewById(R.id.txt_name);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }

        ItemArticleObject object = list.get(position);
        GlideUtil.loadImageWithDefaultPlaceHolder(context, object.getImageUrl(), holder.img_photo);
        holder.txt_article.setText(object.getTitle());
        holder.txt_name.setText(object.getPublisher());

        /**
         * 跳转文章详情页面
         */
        convertView.setOnClickListener(v -> {
            Intent intent = new Intent(context, ItemArticleDetailActivity.class);
            Bundle bundle = new Bundle();
            bundle.putString(CommonConfig.ARTICLE_ID, object.getArticleID());
            bundle.putString(CommonConfig.ARTICLE_TITLE, columnName);
            intent.putExtras(bundle);
            context.startActivity(intent);
        });

        return convertView;
    }


    /**
     * ViewHolder
     */
    class ViewHolder {
        ImageView img_photo;
        TextView txt_article;
        TextView txt_name;
    }
}
